﻿ #region Disclaimer/Info
 
 /////////////////////////////////////////////////////////////////////////////////////////////////
 //
 //   File:		LegacyRouteHandler.cs
 //   Website:		http://dexterblogengine.com/
 //   Authors:		http://dexterblogengine.com/About.ashx
 //   Rev:		1
 //   Created:		19/01/2011
 //   Last edit:		19/01/2011
 //   License:		GNU Library General Public License (LGPL)
 // 
 //   For updated news and information please visit http://dexterblogengine.com/
 //   Dexter is hosted to Codeplex at http://dexterblogengine.codeplex.com
 //   For any question contact info@dexterblogengine.com
 //
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 
 #endregion

using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Dexter.Web.Mvc.Routing.Routes;

namespace Dexter.Web.Mvc.Routing.Routehandlers {
	public class LegacyRouteHandler : IRouteHandler {
		#region IRouteHandler Members

		/// <summary>
		/// 	Provides the object that processes the request.
		/// </summary>
		/// <param name = "requestContext">An object that encapsulates information about the request.</param>
		/// <returns>An object that processes the request.</returns>
		public IHttpHandler GetHttpHandler ( RequestContext requestContext ) {
			return new LegacyHandler ( requestContext );
		}

		#endregion
	}

	// The legacy HttpHandler that handles the request
	public class LegacyHandler : MvcHandler {
		/// <summary>
		/// 	Initializes a new instance of the <see cref = "LegacyHandler" /> class.
		/// </summary>
		/// <param name = "requestContext">The request context.</param>
		/// <exception cref = "T:System.ArgumentNullException">The <paramref name = "requestContext" /> parameter is null.</exception>
		public LegacyHandler ( RequestContext requestContext )
			: base ( requestContext ) {}

		/// <summary>
		/// 	Processes the request by using the specified base HTTP request context.
		/// </summary>
		/// <param name = "httpContext">The HTTP context.</param>
		protected override void ProcessRequest ( HttpContextBase httpContext ) {
			string redirectActionName = ( ( LegacyRoute ) RequestContext.RouteData.Route ).RedirectActionName;

			// ... copy all of the querystring parameters and put them within RouteContext.RouteData.Values
			foreach ( string var in RequestContext.HttpContext.Request.QueryString ) {
				RequestContext.RouteData.Values.Add ( var , RequestContext.HttpContext.Request.QueryString[ var ] );
			}

			VirtualPathData data = RouteTable.Routes.GetVirtualPath ( RequestContext , redirectActionName , RequestContext.RouteData.Values );


			RequestContext.HttpContext.Response.Status = "301 Moved Permanently";
			RequestContext.HttpContext.Response.AppendHeader ( "Location" , data.VirtualPath );
			RequestContext.HttpContext.Response.Redirect ( redirectActionName );
		}
	}
}
